﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DefeatEpidemic.Common;
using DefeatEpidemic.Models;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DefeatEpidemic.API
{
    [Route("api/[controller]")]
    public class AccountController : Controller
    {
        private readonly DefeatEpidemicContext _context;

        public AccountController(DefeatEpidemicContext context)
        {
            _context = context;
        }
        [HttpPost]
        public async Task<Response> WxOauth([FromBody] RequestModels.LoginRequestModel model)
        {
            Response resp = new Response() { code = 1 };
            try
            {
                resp = Lib.AccountLib.GetOpenid(model.loginCode);
                if (resp.code == 1)
                {
                    Dictionary<string, object> dic = resp.data;
                    string oauth_openid = Convert.ToString(dic["openid"]);
                    string session_key = Convert.ToString(dic["session_key"]);
                    string oauth_unionid = dic.ContainsKey("unionid") ? Convert.ToString(dic["unionid"]) : "";//保留，目前没用到  
                    string token = Lib.AccountLib.GetToken(oauth_openid);
                    if (_context.Wxoauths.Count(u => u.open_id == oauth_openid) == 0)
                    {
                        var oauth = new WxOauth()
                        {
                            open_id = oauth_openid,
                            unionid = oauth_unionid,
                            nick_name = model.nick_name,
                            avatar = model.avatar
                        };
                        _context.Wxoauths.Add(oauth);
                        int ret = await _context.SaveChangesAsync();
                        if (ret == 1)
                        {
                            resp.data = new { token = token, open_id = oauth_openid, is_bind = false, role_type = 0, member_id = "" };
                        }
                    }
                    else
                    {
                        var oauth = _context.Wxoauths.Where(u => u.open_id == oauth_openid).FirstOrDefault();
                        if (string.IsNullOrEmpty(oauth.nick_name) || string.IsNullOrEmpty(oauth.avatar))
                        {
                            oauth.nick_name = model.nick_name;
                            oauth.avatar = model.avatar;
                            _context.Wxoauths.Update(oauth);
                            await _context.SaveChangesAsync();
                        }
                        if (oauth.type > 0)
                        {
                            await _context.Entry(oauth).Reference(d => d.member).LoadAsync();
                            resp.message = "微信已绑定";
                            resp.data = new { token = token, open_id = oauth.open_id, is_bind = true, role_type = oauth.type, member_id = oauth.member.id };
                        }
                        else//没有进行微信绑定
                        {
                            resp.message = "success";
                            resp.data = new { token = token, open_id = oauth.open_id, is_bind = false, role_type = 0, member_id = "" };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message},{ex.StackTrace}";
            }
            return resp;
        }
        
    }
}
